<template>
  <basic-container>
    <div>
      <div class="title">
        <el-page-header :icon="ArrowLeft" content="授权列表" @back="proxy.$router.push('/seal/seal-con')"/>
        <div class="seal_name">
          印章编号：{{authSealId}}
        </div>
      </div>
      <div>
        <el-table
            :data="authSealTable"
            header-align="center">
          <el-table-column prop="authSealUserName" label="授权对象" align="center"/>
          <el-table-column prop="authSealRole" label="授权角色" align="center">
            <template #default="scope">
              <div v-if="scope.row.authSealRole === 1">印章使用员</div>
              <div v-else >印章审批员</div>
            </template>
          </el-table-column>
          <el-table-column prop="authSealRange" label="授权范围" align="center">
            <template #default="scope">
              <div v-if="scope.row.authSealRange === 1">全部合同</div>
              <div v-else >指定模板</div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="有效期" align="center">
            <template #default="scope">
              {{scope.row.authStartTime}}
              <div>至</div>
              {{scope.row.authEndTime}}
            </template>
          </el-table-column>
          <el-table-column prop="diffDate" label="授权到期时间" align="center">
            <template #default="scope">
              <div v-if="scope.row.diffDate < 0" style="color: red">已到期</div>
              <div v-else-if="scope.row.diffDate > 0 && scope.row.diffDate < 10" style="color: red">仅剩{{scope.row.diffDate}}天</div>
              <div v-else>{{scope.row.diffDate}}天</div>
            </template>
          </el-table-column>
          <el-table-column prop="authStatus" label="状态" align="center">
            <template #default="scope">
              <div v-if="scope.row.authStatus === 1">正常</div>
              <div v-else style="color: red">失效</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200px" >
            <template #default="scope">
              <el-button type="text" size="large" v-if="scope.row.authStatus === 1" @click="updateSealAuth(scope.$index, scope.row)">编辑</el-button>
              <el-button type="text" size="large" v-else @click="updateSealAuth(scope.$index, scope.row)">重新授权</el-button>
              <el-button type="text" size="large" @click="deleteAuth(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            align="center"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog v-model="dialogTableVisible" title="修改授权" width="600px">
      <el-form
          label-position='right'
          label-width="100px"
          ref="sealAuthFormRef"
          :model="sealAuthForm"
          :rules="sealAuthFormRules"
          size="large"
      >
        <el-form-item label="授权对象" prop="authSealUser">
          <div class="input">
            <el-autocomplete
                v-model="sealAuthForm.authSealUser"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入授权对象"
                @select="handleSelect"
            />
          </div>

        </el-form-item>
        <el-form-item label="授权角色" prop="authSealRole">
          <el-radio-group v-model="sealAuthForm.authSealRole">
            <el-radio :label="1" >印章使用员</el-radio>
            <el-radio :label="2" >印章审批员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="授权范围" prop="authSealRange">
          <el-radio-group v-model="sealAuthForm.authSealRange">
            <el-radio :label="1" >全部合同</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效期" prop="dateValue">
          <el-date-picker
              v-model="sealAuthForm.dateValue"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAuth">确认</el-button>
          <el-button @click="dialogTableVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </basic-container>
</template>

<script setup>
import {ref,getCurrentInstance} from 'vue';
import {
  addSealAuthApi,
  delSealApi,
  delSealAuthApi,
  getSealAuthByIdApi,
  getSealAuthNumBySealIdApi, updateSealAuthApi,
} from '../../api/seal';
import {getDiffDate, getParenthesesStr, transformTime} from '../../utils/util';
import {ElMessage, ElMessageBox} from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue'
import {validatenull} from '../../utils/validate';
import {getUserBySearchApi} from '../../api/user';
const {proxy} = getCurrentInstance()

//接收传过来的路由信息
const authSealId = proxy.$route.query.authSealId

//分页代码
const totalNum = ref(0)
const currentPage=ref(1)
const pageSize=ref(5)

const handleCurrentChange = (currPage) => {
  currentPage.value = currPage
  getSealAuthTable()
  window.scrollTo(0, 175);
}

const handleSizeChange = (val) => {
  pageSize.value=val
  getSealAuthTable()
}

const authSealTable = ref([])
/**
 * 获取授权列表信息
 */
const getSealAuthTable = () => {
  getSealAuthByIdApi(currentPage.value,pageSize.value,authSealId).then(res=>{
    let data = res.data.result
    for (let i = 0; i < data.length; i++){
      data[i].diffDate = getDiffDate(data[i].authEndTime)
      data[i].authStartTime = transformTime(data[i].authStartTime)
      data[i].authEndTime = transformTime(data[i].authEndTime)
    }
    authSealTable.value = data
  })
}
getSealAuthTable()

/**
 * 根据id获取授权印章数量
 */
const getSealAuthNumBySealId = () => {
  getSealAuthNumBySealIdApi(authSealId).then(res=>{
    totalNum.value = res.data.result
  })
}
getSealAuthNumBySealId()


//新增授权弹窗是否打开
const dialogTableVisible = ref(false)

const sealAuthFormRef = ref(null)
const sealAuthFormRules = ref({
  authSealUser: [ {required: true, message: "请输入授权对象",trigger: "change"} ],
  authSealRole: [ {required: true, message: '请选择授权角色', trigger: 'change'} ],
  authSealRange: [ {required: true, message: '请选择授权范围', trigger: 'change'} ],
  dateValue: [ {type: 'array',required: true, message: '请选择授权日期', trigger: 'change'} ]
})
/**
 * 印章授权表单
 * @type {Ref<UnwrapRef<{}>>}
 */
const sealAuthForm = ref({
  uuid: '',
  authSealId: '',
  authSealUser: '',
  authSealRole: '',
  authSealRange: '',
  authStartTime: '',
  authEndTime: '',
  authStatus: '',
  dateValue: []
})

/**
 * 根据用户输入实时获取数据库中的信息
 * @param queryString
 * @param callback
 */
const querySearchAsync = (queryString,callback) => {
  let list = [{}]
  if(!validatenull(queryString)){
    getUserBySearchApi(queryString).then(res=>{
      let data = res.data.result
      if(!validatenull(data)) {
        //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
        for (let i of data) {
          i.value = i.userName + "(" + i.userId + ")";  //将想要展示的数据作为value
        }
        list = data;
      }else {
        data.value = "该用户不存在"
        list.push(data)
      }
      callback(list);
    })
  }
}

const handleSelect = (item) => {
  // console.log(sealAuthForm.value.authSealUser)
}

/**
 * 打开新增栏
 */
const updateSealAuth = (index,row) => {
  //sealAuthFormRef.value.resetFields()
  sealAuthForm.value.uuid= row.uuid
  sealAuthForm.value.authSealId = authSealId
  sealAuthForm.value.authSealUser = row.authSealUserName+ '(' +row.authSealUser + ")"
  sealAuthForm.value.authSealRole = row.authSealRole
  sealAuthForm.value.authSealRange = row.authSealRange
  sealAuthForm.value.dateValue.push(new Date(row.authStartTime))
  sealAuthForm.value.dateValue.push( new Date(row.authEndTime))
  dialogTableVisible.value = true

}

/**
 * 新增授权印章
 */
const submitAuth = () => {
  sealAuthFormRef.value.validate((valid)=>{
    if(valid){
      sealAuthForm.value.authStartTime = sealAuthForm.value.dateValue[0]
      sealAuthForm.value.authEndTime = sealAuthForm.value.dateValue[1]
      sealAuthForm.value.authSealUser = getParenthesesStr(sealAuthForm.value.authSealUser)
      updateSealAuthApi(sealAuthForm.value).then(res=>{
        let data = res.data.result
        if(data === "success"){
          ElMessage.success("修改授权成功！")
          dialogTableVisible.value = false
          getSealAuthTable()
          getSealAuthNumBySealId()
        }else {
          ElMessage.error("修改授权失败，请重试!")
        }
      })
    }
  })
}

/**
 * 删除授权
 */
const deleteAuth = (index,row) => {
  ElMessageBox.confirm(
      '确认删除该授权吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        delSealAuthApi(row.uuid).then(res=>{
          if(res.data.responseSuccess){
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getSealAuthTable()
            getSealAuthNumBySealId()
          }else {
            ElMessage({
              type: 'error',
              message: '删除失败，请重试',
            })
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

</script>

<style scoped>
/deep/ .el-card__body {
  margin: 10px 20px;
}
.title{
  margin: 20px 20px;
}
.seal_name{
  margin-top: 20px;
  margin-bottom: 20px;
}
/* 表格样式 */
/deep/ .el-table{
  margin-top: 10px;
}
/deep/ .el-table th{
  border-bottom: 1px solid #e8eaec !important;
}
/deep/ .el-table__header-wrapper th{
  background: #f8f8f9;
  color: #515a6e;
}

/deep/ .el-pagination{
  margin: 30px 0 10px 0;
}
</style>
